package com.mianle.userapi.util;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WeixinUtil {


    @Value("${wx.config.appid}")
    private String appid;

    @Value("${wx.config.secret}")
    private String secret;


    private static final String WEIXIN_WEB_OAUTH_ACCESS_TOKEN_PREFIX = "weixin:web:oauth:access_token:";



    @Autowired
    private RedisTemplate redisTemplate;


    /**
     *
     *
     * 前置说明:code说明 ： code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
     *
     * 通过code换取网页授权access_token
     *
     * 如果网页授权的作用域为snsapi_base，则本步骤中获取到网页授权access_token的同时，也获取到了openid，snsapi_base式的网页授权流程即到此为止
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    public JsonNode snsapi_oauth2_access_token(String code) {
        if (!org.apache.commons.lang3.StringUtils.isEmpty(code)) {
            //获取openid和access_token的连接
            String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
                    "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
            //获取返回的code


            //https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8cb4511f821ff6f4&secret=5c939c9b1f5355d7d963149479e307b6&code=071AIO8Y0JKX712ZkR8Y0dsL8Y0AIO8H&grant_type=authorization_code

            //{"access_token":"8_8I1Jd4Js2arYPNSqG4UUwYTt1CvjAdYhkh4U510IXPwXxxqvpz7pgnyL9n39YwZlm6BjzBVm5ccZ9WeaU0ZlJw","expires_in":7200,"refresh_token":"8_tgspJrkQWyutN-8LsQEZbKTUMjR0g-mGYJRdTBXPdugIv0u_MiFP9E6vwaiaDH6-4F4njLzEootDREYxLIAfFQ","openid":"oFgpt0Xd-RYJkJM3VzoumzJyFFUs","scope":"snsapi_base"}

            String response = HttpUtil.get(requestUrl);

            log.info("#getAccessTokenWeb# requestUrl:{} response:{}",requestUrl,response);

            //成功返回的json串 {"access_token":"8_8I1Jd4Js2arYPNSqG4UUwYTt1CvjAdYhkh4U510IXPwXxxqvpz7pgnyL9n39YwZlm6BjzBVm5ccZ9WeaU0ZlJw","expires_in":7200,"refresh_token":"8_tgspJrkQWyutN-8LsQEZbKTUMjR0g-mGYJRdTBXPdugIv0u_MiFP9E6vwaiaDH6-4F4njLzEootDREYxLIAfFQ","openid":"oFgpt0Xd-RYJkJM3VzoumzJyFFUs","scope":"snsapi_base"}
            //失败返回的json串 {"errcode":40029,"errmsg":"invalid code"}


            JsonNode jsonObject = JsonUtil.fromString(response);
            if (jsonObject.get("access_token")!=null && StringUtils.isNotEmpty(jsonObject.get("access_token").asText())) {
                String openid = jsonObject.get("openid").asText();
                //redisTemplate.opsForValue().set(WEIXIN_WEB_OAUTH_ACCESS_TOKEN_PREFIX+openid,response,7200, TimeUnit.SECONDS);
            }


            return jsonObject;
            //String access_token = jsonObject.get("access_token").asText();
            //String openId = jsonObject.get("openid").asText();
        }
        return null;
    }


    /**
     * scope为 snsapi_userinfo网页授权获取用户基本信息
     *
     * @param openid
     * @return
     * {    "openid":" OPENID",
    " nickname": NICKNAME,
    "sex":"1",
    "province":"PROVINCE"
    "city":"CITY",
    "country":"COUNTRY",
    "headimgurl":    "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
    "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
    }


    {"errcode":48001,"errmsg":"api unauthorized, hints: [ req_id: yysYGa0023s160 ]"}
     */
    public JsonNode snsapi_userinfo_access_token(String openid,String access_token) {
        if (!org.apache.commons.lang3.StringUtils.isEmpty(openid)) {
            //获取openid和access_token的连接
            /**Object o = redisTemplate.opsForValue().get(WEIXIN_WEB_OAUTH_ACCESS_TOKEN_PREFIX + openid);
            if (o != null) {
                JsonNode jsonObject = JsonUtil.fromString(o.toString());
                access_token = jsonObject.get("access_token").asText();
            }**/

            String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
            //获取返回的code

            String response = HttpUtil.get(requestUrl);

            log.info("#getUserInfoWeb# requestUrl:{} response:{}",requestUrl,response);


            JsonNode jsonObject = JsonUtil.fromString(response);

            return jsonObject;
        }
        return null;
    }







}
